<?php

namespace App\Exports;

use App\Models\CommodityActivity;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Maatwebsite\Excel\Concerns\FromQuery;

class CultivationAwardExport extends BaseExport implements FromQuery

{
    public function headings(): array
    {
        return [
            '活动编号',
            '商品名称',
            '商品编号',
            '供应商',
            '状态',
            '是否激活',
            '总库存',
            '运费',
            '包邮规则',
            '活动时间',
            '商品类别',
            '添加时间',
            '培养奖金额',
            '培养奖数量',
            '培养奖总金额',
        ];
    }

    public function map($row): array
    {
        $row = $row->toArray();

        $freeShippingConditions = [];
        $freeShippingTips = '包邮';
        if ($row['free_shipping_maximum'] && $row['free_shipping_maximum'] > 0) {
            $freeShippingConditions[] = '小于' . $row['free_shipping_maximum'];
        }
        if ($row['free_shipping_minimal'] && $row['free_shipping_minimal'] > 0) {
            $freeShippingConditions[] = '大于等于' . $row['free_shipping_minimal'];
        }
        if (count($freeShippingConditions) > 0) {
          $freeShippingTips = implode(' ', $freeShippingConditions) . '件包邮'; // 免邮条件
        }

        return [
            $row['id'], // 活动编号
            $row['commodity']['name'], // 商品名称
            $row['commodity']['numbering'], // 商品编号
            $row['commodity']['supplier']['name'], // 供应商
            CommodityActivity::STATUS_MAP[$row['status']], // 状态
            CommodityActivity::LOCKING_MAP[$row['locking']], // 是否激活
            array_reduce($row['skus'], fn ($stock, $sku) => $stock + $sku['stock'], 0), // 总库存
            number_format($row['freight'] / 100, 2), // 运费
            $freeShippingTips, // 包邮规则
            sprintf('%s 至 %s', $row['panic_buying_start_time'], $row['panic_buying_end_time']), // 活动时间
            $row['commodity']['category']['name'], // 商品类别
            $row['created_at'], // 添加时间
            1, // 培养奖金额
            $row['statistics']['number_of_cultivation_awards'], // 培养奖数量
            number_format($row['statistics']['total_amount_of_cultivation_awards'] / 100, 2), // 培养奖总金额
        ];
    }

    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function query()
    {
        return CommodityActivity::query()
            ->withTrashed()
            ->with(['statistics', 'skus', 'commodity' => function (BelongsTo $builder) {
                $builder
                    ->withTrashed()
                    ->with(['supplier', 'category']);
            }])
            ->when(
                $this->request['name'] ?? '' || $this->request['numbering'] ?? '' || $this->request['category'] ?? 0 || $this->request['supplier_id'] ?? 0,
                function (Builder $builder) {
                    $builder
                        ->join('commodities', 'commodities.id', '=', 'commodity_activities.commodity_id')
                        ->when($this->request['name'] ?? '', function ($builder, $name) {
                            $builder->where('commodities.name', 'like', "$name%");
                        })
                        ->when($this->request['numbering'] ?? '', function ($builder, $numbering) {
                            $builder->where('commodities.numbering', 'like', "$numbering%");
                        })
                        ->when($this->request['category'] ?? 0, function ($builder, $category) {
                            $builder->where('category_id', $category);
                        })
                        ->when($this->request['supplier_id'] ?? 0, function ($builder, $supplierId) {
                            $builder->where('supplier_id', $supplierId);
                        });
                })
            ->when($this->request['locking'] ?? 0, function (Builder $builder, $locking) {
                $builder->where('locking', $locking);
            })
            ->whereHas('statistics');
    }
}
